package com.liuyjy.base.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * @Author liuyjy
 * @Date 2025/2/6 14:19
 * @Description: 生成和验证token
 **/
public class TokenUtil {


    public static String secretStatic;
    public static Long expirationStatic;
    @Value("${jwt.secret:liuyjy}")
    private String secret = "liuyjy";
    /**
     * token过期时间 秒
     */
    @Value("${jwt.expiration:}")
    private Long expiration = 72000000L;


    /**
     * 生成token
     *
     * @param username 用户名
     * @return token
     */
    public static String generateToken(String username) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + expirationStatic);

        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(SignatureAlgorithm.HS512, secretStatic)
                .compact();
    }

    /**
     * 从token中获取用户名
     *
     * @param token token
     * @return 用户名
     */
    public static String getUsernameFromToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(secretStatic)
                .parseClaimsJws(token)
                .getBody();
        return claims.getSubject();
    }

    /**
     * 验证token
     *
     * @param token token
     * @return true/false
     */
    public static boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(secretStatic).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static void main(String[] args) {
        String token = generateToken("liuyjy");
        System.out.println(token);
        System.out.println(getUsernameFromToken(token));
        System.out.println(validateToken(token));
    }

    @PostConstruct
    public void init() {
        secretStatic = secret;
        expirationStatic = expiration;
    }
}
